package svc

import (
	"net/http"

	"gitee.com/gao-deguang/easy-chat/apps/im/models"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/websocket"
	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/socialclient"
	"gitee.com/gao-deguang/easy-chat/apps/task/mq/internal/config"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	config.Config
	*redis.Redis

	WsClients map[string]websocket.Client

	models.ChatLogModel
	models.ConversationModel

	Social socialclient.Social
}

func NewServiceContext(c config.Config) *ServiceContext {
	ctx := &ServiceContext{
		Config:            c,
		Redis:             redis.MustNewRedis(c.Redisx),
		ChatLogModel:      models.MustChatLogModel(c.Mongo.Url, c.Mongo.DB),
		ConversationModel: models.MustConversationModel(c.Mongo.Url, c.Mongo.DB),
		Social:            socialclient.NewSocial(zrpc.MustNewClient(c.SocialRPC)),
		WsClients:         make(map[string]websocket.Client),
	}
	token, err := ctx.GetSystemToken()
	if err != nil {
		panic(err)
	}

	header := http.Header{}
	header.Set("Authorization", token)

	for _, serverHost := range c.Ws.Host {
		WsClient := websocket.NewClient(serverHost, websocket.WithClientHeader(header))
		ctx.WsClients[serverHost] = WsClient
		logx.Info("mq连接websocket:", serverHost)
	}
	for k, v := range ctx.WsClients {
		logx.Info(k, v)
	}

	return ctx
}

func (svc *ServiceContext) GetSystemToken() (string, error) {
	return svc.Redis.Get(constant.REDIS_SYSTEM_ROOT_TOKEN)
}
